﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using DNT.RavenQA.Core.Extensions;
using StructureMap;

namespace DNT.RavenQA.Web.Infrastructure.IoC
{
    public class StructureMapControllerActivator : IControllerActivator
    {
        private readonly IContainer _container;

        public StructureMapControllerActivator(IContainer container)
        {
            container.EnsureIsNotNull("container");
            _container = container;
        }

        public IController Create(RequestContext requestContext, Type controllerType)
        {
            if (controllerType.IsNull())
                return null;

            IController controller;

            try { controller = (IController)_container.GetInstance(controllerType); }
            catch (StructureMapException exc) { throw new InvalidOperationException("Culd not build the requested controller.", exc); }

            return controller;
        }
    }
}